﻿using System;
using System.Linq;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace MvvmInteractivity.Sample.ViewModels
{
	public class ClosableViewModel : ViewModelBase, IClosableViewModel, IDragAndDrop
	{
		public event EventHandler<CloseEventArgs> RequestClose;

		public void Close()
		{
			OnRequestClose(new CloseEventArgs());
		}

		public void OnRequestClose(CloseEventArgs e)
		{
			var local = RequestClose;
			if (local != null)
			{
				local(this, e);
			}
		}

		private RelayCommand closeCommand;
		public ICommand CloseCommand
		{
			get
			{
				if (closeCommand == null)
				{
					closeCommand = new RelayCommand(OnCloseCommandExecuted);
				}

				return closeCommand;
			}
		}

		private string dropData;

		public string DropData
		{
			get
			{
				return dropData;
			}
			set
			{
				dropData = value;
				RaisePropertyChanged("DropData");
			}
		}

		private void OnCloseCommandExecuted()
		{
			OnRequestClose(new CloseEventArgs());
		}

		/// <summary>
		/// Gets a value indicating whether Drag operation currently available or not.
		/// </summary>
		public bool IsDragAvailable
		{
			get
			{
				return true;
			}
		}

		/// <summary>
		/// Gets the data to be dragged.
		/// </summary>
		public object DragData
		{
			get
			{
				return "Raw string";
			}
		}

		/// <summary>
		/// Gets format for drag operation.
		/// </summary>
		public string DragFormat
		{
			get
			{
				return "System.String";
			}
		}

		/// <summary>
		/// Gets supported drop formats.
		/// </summary>
		public string[] DropFormats
		{
			get
			{
				//Support only FileDrop.
				return new[] {"FileDrop"};
			}
		}

		/// <summary>
		/// Performs processing of drop. Returns true if data has been processed. Return value
		/// can be used in case when object supports many drop formats to notify that processing was
		/// successful.
		/// </summary>
		/// <param name="format">Format of data being dropped.</param>
		/// <param name="data">Data being dropped.</param>
		/// <returns>True if data has been processed, false otherwise.</returns>
		public bool DoDrop(string format, object data)
		{
			var success = false;
			if (format == "FileDrop")
			{
				DropData = ((string[])data).FirstOrDefault();
				success = true;
			}

			return success;
		}
	}
}